package com.haust.community.controller;

import com.haust.community.event.Event;
import com.haust.community.event.EventProducer;
import com.haust.community.pojo.User;
import com.haust.community.service.LikeService;
import com.haust.community.utils.CommunityConstant;
import com.haust.community.utils.CommunityUtil;
import com.haust.community.utils.HostHolder;
import com.haust.community.utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: csp1999
 * @Date: 2020/11/27/20:59
 * @Description: 点赞controller
 */
@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户点赞操作
     *
     * @param entityType   帖子实体类型
     * @param entityId     帖子实体id
     * @param entityUserId 被点赞实体的用户id
     * @return
     */
    @RequestMapping(path = "/like", method = RequestMethod.POST)
    @ResponseBody
    public String like(
            int entityType, int entityId, int entityUserId, int postId) {
        // 获取登录用户
        User user = hostHolder.getUser();

        // 进行点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        // 点赞的数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 点赞的状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        // 返回的结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        // 触发点赞事件 0未点赞/1已点赞
        if (likeStatus == 1) {
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)// 主题: 点赞
                    .setUserId(hostHolder.getUser().getId())// 用户id
                    .setEntityType(entityType)// 实体类型
                    .setEntityId(entityId)// 实体id
                    .setEntityUserId(entityUserId)// 被点赞实体的用户id
                    .setData("postId", postId);// 帖子id 放入data 这个map集合

            // 消息生产者通知消息消费者
            eventProducer.fireEvent(event);
        }

        if (entityType == ENTITY_TYPE_POST){
            // 获取帖子分数集合的key
            String redisPostScoreKey = RedisKeyUtil.getPostScoreKey();
            // 向 redisPostScoreKey 中存入帖子id
            redisTemplate.opsForSet().add(redisPostScoreKey, postId);
        }

        return CommunityUtil.getJSONString(0, null, map);
    }
}

